use std::fmt::Display;

fn main() {
  let mut link = Link::new();
  link.prepend(5).prepend(4).prepend(3).prepend(2).prepend(1);

  println!("{}", link);
}

struct Node {
  value: usize,
  next: Option<Box<Node>>
}

struct Link {
  len: usize,
  head: Option<Box<Node>>
}

impl Node {
    fn new(value: usize) -> Self {
      Node { value, next: None } 
    }
}
impl Link {
    fn new() -> Self {
      Link { len: 0, head: None }
    }

    fn prepend(&mut self, value: usize) -> &mut Self {
      let mut node = Box::new(Node::new(value));
      match self.head {
          None => self.head = Some(node),
          Some(_) => {
            node.next = self.head.take();
            self.head = Some(node)
          }
      }
      self.len += 1;
      self
    }
}

impl Display for Link {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.head.is_none() {
           write!(f, "None\n")?;
        } else {
            let mut next = self.head.as_ref();
            while let Some(node) = next {
                write!(f, "{} -> ", node.value)?;
                 next = node.next.as_ref();
            }
            write!(f, "None\n")?;
        }
        Ok(())
    }
}